package com.baizhi.service.impl;

import com.baizhi.dao.EmpDAO;
import com.baizhi.dao.impl.EmpDAOImpl;
import com.baizhi.entity.Emp;
import com.baizhi.service.EmpService;
import com.baizhi.util.JDBCUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class EmpServiceImpl implements EmpService {
    private EmpDAO ed = new EmpDAOImpl();
    @Override
    public List<Emp> queryAllEmps() {
        return ed.selectAllEmps();
    }

    @Override
    public void removeEmp(int id) {
        Connection conn = null;
        try{
            conn = JDBCUtil.getConnection();
            conn.setAutoCommit(false);
            ed.deleteEmpById(id);
            conn.commit();
        }catch(Exception e){
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }finally {
            JDBCUtil.close(conn);
        }
    }

    @Override
    public void registEmp(Emp emp) {
        Connection conn = null;
        try{
            conn = JDBCUtil.getConnection();
            conn.setAutoCommit(false);
            ed.insertEmp(emp);
            conn.commit();
        }catch(Exception e){
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }finally {
            JDBCUtil.close(conn);
        }
    }

    @Override
    public Emp queryById(int id) {
        return ed.selectById(id);
    }

    @Override
    public void changeEmp(Emp emp) {
        Connection conn = null;
        try{
            conn = JDBCUtil.getConnection();
            conn.setAutoCommit(false);
            ed.updateEmp(emp);
            conn.commit();
        }catch(Exception e){
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }finally {
            JDBCUtil.close(conn);
        }
    }
}
